package com.example.k8s.hello.boot.oss.conf;

import com.example.k8s.hello.boot.oss.service.IOssService;
import com.example.k8s.hello.boot.oss.service.OssService;
import com.example.k8s.hello.boot.oss.template.OssTemplate;
import com.example.k8s.hello.boot.oss.template.S3Template;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

import java.net.URI;

/**
 * @Author 公众号：码猿技术专栏
 * @Description oss配置bean
 * @ClassName OssAConfiguration
 * @Date 2023/3/18 18:23
 **/
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(OssProperties.class)
public class OssAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public S3Client createOssClient(OssProperties properties) {
        // 创建 S3 客户端
        S3Client s3 = S3Client.builder()
                .serviceConfiguration(c ->c.pathStyleAccessEnabled(true))
                .region(Region.of(properties.getRegion())) // 替换为你的区域
                .endpointOverride(URI.create(properties.getEndpoint()))
                .credentialsProvider(
                        StaticCredentialsProvider.create(
                                AwsBasicCredentials.create(properties.getAccessKey(), properties.getSecretKey())))

                .build();

        return s3;
    }

    @Bean
    @ConditionalOnMissingBean
    public OssTemplate ossTemplate(S3Client client, OssProperties properties){
        return new S3Template(client, properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public IOssService iOssService(OssTemplate ossTemplate){
        return new OssService(ossTemplate);
    }
}
